﻿using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using CSharpHelpers.IOs;

namespace CSharpHelpers.Commons
{
    class Common
    {
        #region 重启程序三种写法
        //System.Windows.Forms.Application.Restart();
        //Application.Current.Shutdown();

        //System.Reflection.Assembly.GetEntryAssembly();
        //string startpath = System.IO.Directory.GetCurrentDirectory();
        //System.Diagnostics.Process.Start(startpath + "\\WpfVenderFrontdesk.exe");
        //Application.Current.Shutdown();

        //Process p = new Process();
        //p.StartInfo.FileName = System.AppDomain.CurrentDomain.BaseDirectory + "WpfVenderFrontdesk.exe";
        //p.StartInfo.UseShellExecute = false;
        //p.Start();
        //Application.Current.Shutdown();
        #endregion

        #region 只运行一个实例（显示已经运行实例的界面）

        private static void OnlyRunOneInstance(string consoleName)
        {
            Process instance = RunningInstance();
            if (instance == null)
            {
                Process.Start(Const.ConsolePath, consoleName);
            }
            else
            {
                HandleRunningInstance(instance);
            }

        }

        //返回正在运行的程序进程
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/ ", "\\ ") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }

            return null;//第一次运行，返回null
        }

        //显示正在运行的进程当前窗口
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //置窗口为正常状态
            SetForegroundWindow(instance.MainWindowHandle);
        }

        //调用系统api
        [DllImport("User32.dll ")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll ")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;

        #endregion

        //System.Windows.Forms.Application.DoEvents();

        #region 从A程序中打开B程序
        /// <summary>
        /// 从A程序中打开B程序
        /// </summary>
        /// <returns></returns>
        public static bool OpenConsoleApplication()
        {
            try
            {
                // 写法一
                var process = Process.Start(Const.ConsolePath + "AutoVenderConsole.exe", Const.ConsolePath);
                //var process = Process.Start(PageConst.ConsoleDebugPath + "AutoVenderConsole.exe", PageConst.ConsoleDebugPath);
                if (process == null)
                {
                    return false;
                }

                return true;


                // 写法二
                //var startInfo = new ProcessStartInfo
                //{
                //    Arguments = consoleName,
                //    FileName = PageConst.ConsolePath
                //};

                //Process.Start(startInfo);
            }
            catch (Exception ex)
            {
                SystemLog.Error("打开后台程序出错: " + ex);
                return false;
            }
        }

        #endregion

        // 把当前窗体设为主窗体
        //this.Owner = Application.Current.MainWindow;
    }
}
